<template>
  <div class="container">
    <Row style="margin-bottom: 3px;">
      <Col span="24">
        <Button type="info" ghost :style="{width: '100%'}" @click="_openWebview('https://www.baidu.com')">打开浏览器</Button>
      </Col>
    </Row>

    <Row style="margin-bottom: 3px;">
      <Col span="5">
        <Input v-model="columnKey" placeholder="请输入数据列KEY"/>
      </Col>
      <Col span="5">
        <Input v-model="columnTitle" placeholder="请输入数据列名"/>
      </Col>
      <Col span="4">
        <Select v-model="dataType" placeholder="请选择数据类型">
          <Option value="str">字符串</Option>
          <Option value="arr">数组</Option>
          <Option value="obj">对象</Option>
          <Option value="num">数字</Option>
        </Select>
      </Col>
      <Col span="4">
        <Select v-model="contentType" placeholder="请选择内容类型">
          <Option value="txt">文本</Option>
          <Option value="img">图片</Option>
          <Option value="url">URL</Option>
          <Option value="video">视频</Option>
          <Option value="audio">音频</Option>
        </Select>
      </Col>
      <Col span="6" class="top-operation-area">
        <Button type="success" class="top-btn" @click="addColumnClickHandle">添加数据列</Button>
        <Button type="success" class="top-btn" @click="managerColumnClickHandle">管理数据列</Button>
      </Col>
    </Row>

    <Table :columns="selectDatabookData.columns" :data="selectDatabookData.data" :show-header="false" size="small">
      <template slot="header">
        <table cellspacing="0" cellpadding="0" border="0" style="width: 100%;">
          <thead>
            <tr>
              <th v-for="item in selectDatabookData.columns" :key="item.key">
                <div class="ivu-table-cell" style="width: 100%;">
                  <template v-if="item.slot != 'action'">
                    <Tooltip :content="item.key + '[' + item.title + ']'" style="width: inherit;">
                      <div class="table-header-title">
                        {{item.key}}[{{item.title}}]
                      </div>
                      <Button v-if="item.contentType == 'img'" size="small"
                        type="success"
                        ghost
                        class="table-header-btn"
                        style="right: 34px;"
                        @click="collectImageClickHandle(item.key)">采集</Button>
                      <Button size="small"
                        type="error"
                        ghost
                        class="table-header-btn"
                        @click="deleteColumnClickHandle(item.key)">删除</Button>
                    </Tooltip>
                  </template>
                  <template v-else>
                    <span v-if="columns.length > 0">
                      {{item.title}}
                    </span>
                  </template>
                </div>
              </th>
            </tr>
          </thead>
        </table>
      </template>

      <template v-for="item in selectDatabookData.columns" slot-scope="{row, index}" :slot="item.slot">
        <div v-if="item.contentType == 'url'" :key="item.key + '_' + index">
          <div v-if="item.dataType == 'arr'">
            <div v-for="(aHref, aIndex) in row[item.key]" :key="item.key + '_' + index + '_href_' + aIndex" style="margin: 10px 0px;">
              <a :href="aHref" target="_blank">{{aHref}}</a>
            </div>
          </div>
          <div v-else>
            <!-- <a :href="row[item.key]" target="_blank">{{row[item.key]}}</a> -->
            <a href="javascript:void(0)" target="_self" @click="_openWebview(row[item.key])">{{row[item.key]}}</a>
          </div>
        </div>
        <div v-else-if="item.contentType == 'img'" :key="item.key + '_' + index">
          <div v-if="item.dataType == 'arr'">
            <div v-for="(aHref, aIndex) in row[item.key]" :key="item.key + '_' + index + '_href_' + aIndex" style="margin: 10px 0px;">
              <img v-if="aHref" :src="ImgProxyUrl + _base64Encode(encodeURI(aHref))" :alt="aHref" style="width: 100%;" />
            </div>
          </div>
          <div v-else>
            <img v-if="row[item.key]" :src="ImgProxyUrl + _base64Encode(encodeURI(row[item.key]))" :alt="row[item.key]" style="width: 100%;" />
          </div>
        </div>
        <div v-else-if="item.contentType == 'video'" :key="item.key + '_' + index">
          <MediaVideo v-if="row[item.key]" :src="row[item.key]"></MediaVideo>
        </div>
        <div v-else-if="item.contentType == 'audio'" :key="item.key + '_' + index">
          <MediaAudio v-if="row[item.key]" :src="row[item.key]"></MediaAudio>
        </div>
        <div v-else-if="item.contentType == 'txt'" :key="item.key + '_' + index">
          <div v-if="item.dataType == 'arr'">
            <div v-for="(txtItem, aIndex) in row[item.key]" :key="item.key + '_' + index + '_href_' + aIndex" style="margin: 10px 0px;">
              {{txtItem}}
            </div>
          </div>
          <div v-else>
            {{row[item.key]}}
          </div>
        </div>
        <div v-else :key="item.key + '_' + index">
          {{row[item.key]}}
        </div>
      </template>

      <template slot-scope="{row, index}" slot="action">
          <Button size="small" style="margin-right: 5px" @click="moveUpClickHandle(row, index)">上移</Button>
          <Button size="small" style="margin-right: 5px" @click="moveDownClickHandle(row, index)">下移</Button>
          <Button type="primary" size="small" style="margin-right: 5px" @click="editDataClickHandle(row, index)">修改</Button>
          <Button type="error" size="small" @click="deleteDataClickHandle(row, index)">删除</Button>
      </template>

      <template slot="footer">
        <table cellspacing="0" cellpadding="0" border="0" style="width: 100%;">
          <tbody>
            <tr>
              <td v-for="item in selectDatabookData.columns" :key="item.key">
                <div class="ivu-table-cell">
                  <Input v-model="newDataItem[item.key]" v-if="item.slot != 'action'" :placeholder="'请输入' + item.title" type="textarea" :rows="3" size="small" />
                  <Button v-if="item.slot == 'action' && columns.length > 0"
                    type="success"
                    size="small"
                    @click="addDataClickHandle">添加</Button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </template>
    </Table>

    <Modal
        v-model="modal.editData.isShow"
        title="数据详情"
        :mask-closable="false">
        <p>
          <Row v-for="item in columns" :key="item.key" :gutter="12" style="margin-bottom: 10px;">
            <Col span="6">
              <span style="width: 100%; line-height: 32px; text-align: right; display: inline-block;">{{item.title}}:</span>
            </Col>
            <Col span="12">
              <Input v-if="item.dataType != 'arr'" v-model="showData[item.key]" :placeholder="'请输入' + item.title"/>
              <Input v-else v-model="showData[item.key]" :placeholder="'请输入' + item.title" type="textarea" :rows="3"/>
            </Col>
          </Row>
        </p>
        <div slot="footer">
          <Button @click="modal.editData.isShow = false">关闭</Button>
          <Button type="success" @click="saveDataClickHandle">保存</Button>
        </div>
    </Modal>

    <Modal
        v-model="webview.isShow"
        title="浏览器"
        width="100%"
        class-name="vertical-center-modal"
        :mask-closable="false">
        <div slot="header">
        </div>
        <webview :url="webview.url" :isShow="webview.isShow" :style="{height: '100%', width: '100%'}" ref="wedview"></webview>
        <div slot="footer">
        </div>
    </Modal>

    <ManagerColumns :datas="columns" ref="managerColumns"></ManagerColumns>
  </div>
</template>
<script>
import Webview from '_c/webview'
import ManagerColumns from '_c/databook-editor/manager-columns.vue'
import {MediaAudio, MediaVideo} from '_c/media'
import config from '@/config'
export default {
  name: 'DatabookEditor',
  components: {
    Webview,
    ManagerColumns,
    MediaAudio,
    MediaVideo
  },
  props: {
    columns: {
      type: Array,
      default: () => {
        return []
      }
    },
    data: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    return {
      ImgProxyUrl: config.urls.imgProxyUrl,
      columnKey: '',
      columnTitle: '',
      dataType: '',
      contentType: '',
      newDataItem: {},
      modal: {
        editData: {
          isShow: false
        }
      },
      webview: {
        url: '',
        isShow: false
      },
      showData: {},
      editDataIndex: -1
    }
  },
  computed: {
    selectDatabookData () {
      let columnArr = []
      for (let i in this.columns) {
        let item = this.columns[i]
        item.slot = item.key

        columnArr.push(item)
      }

      let columns = JSON.parse(JSON.stringify([].concat(columnArr).concat([
        {
          title: '操作',
          slot: 'action'
        }
      ])))
      return {
        columns: columns,
        data: this.columns.length > 0 ? this.data : []
      }
    }
  },
  methods: {
    addColumnClickHandle () {
      if (!this.columnKey) {
        this.$Message.error('数据列KEY不能为空')
        return
      }

      if (!this.columnTitle) {
        this.$Message.error('数据列名不能为空')
        return
      }

      if (!this.dataType) {
        this.$Message.error('请选择数据类型')
        return
      }

      if (!this.contentType) {
        this.$Message.error('请选择内容类型')
        return
      }

      let isExist = this.columns.find(item => {
        return item.key === this.columnKey || item.title === this.columnTitle
      })

      if (isExist) {
        this.$Message.error('数据列名和数据列名不允许重复')
        return
      }

      this.columns.push({
        title: this.columnTitle,
        key: this.columnKey,
        dataType: this.dataType,
        contentType: this.contentType
      })
    },
    managerColumnClickHandle () {
      this.$refs.managerColumns.show()
    },
    collectImageClickHandle (columnKey) {
      this.$emit('collectImage', columnKey)
    },
    deleteColumnClickHandle (columnKey) {
      let index = this.columns.findIndex(item => {
        return item.key === columnKey
      })

      if (index > -1) {
        this.columns.splice(index, 1)
      }
    },
    addDataClickHandle () {
      let newDataItem = JSON.parse(JSON.stringify(this.newDataItem))
      let dataItem = {}

      for (let key in newDataItem) {
        let value = newDataItem[key]

        let column = this.columns.find(item => {
          return item.key === key
        })
        let dataType = column.dataType

        if (dataType === 'arr') {
          value = value.replace(/\r\n/g, '\n')
          let valueArr = value.split('\n')
          value = valueArr
        }

        dataItem[key] = value
      }

      this.data.push(dataItem)
    },
    editDataClickHandle (row, index) {
      let showData = this.data[index]
      this.showData = {}

      for (let key in showData) {
        let value = showData[key]

        let column = this.columns.find(item => {
          return item.key === key
        })
        let dataType = column ? column.dataType : 'str'

        if (dataType === 'arr') {
          value = value.join('\n')
        }

        this.showData[key] = value
      }

      this.editDataIndex = index
      this.modal.editData.isShow = true
    },
    deleteDataClickHandle (row, index) {
      // 根据指定下标删除元素
      this.data.splice(index, 1)
    },
    moveUpClickHandle (row, index) {
      if (index > 0) {
        this.data[index] = this.data.splice(index - 1, 1, this.data[index])[0]
      }
    },
    moveDownClickHandle (row, index) {
      if (index < this.data.length - 1) {
        this.data[index] = this.data.splice(index + 1, 1, this.data[index])[0]
      }
    },
    saveDataClickHandle () {
      for (let key in this.showData) {
        let value = this.showData[key]

        let column = this.columns.find(item => {
          return item.key === key
        })
        let dataType = column ? column.dataType : 'str'

        if (dataType === 'arr') {
          value = value.replace(/\r\n/g, '\n')
          let valueArr = value.split('\n')
          value = valueArr
        }

        // this.data[this.editDataIndex][key] = value
        this.$set(this.data[this.editDataIndex], key, value)
      }

      this.modal.editData.isShow = false
    },
    _openWebview (url) {
      // this.webview.url = url
      this.webview.isShow = true
      this.$refs.wedview._openWebview(url, this.columns)
    },
    _base64Encode (val) {
      return btoa(val)
    }
  }
}
</script>

<style lang="less" scoped>
  .container {
    .table-header-title {
      overflow: hidden;
      text-overflow: ellipsis;
      width: 100%;
      white-space: nowrap;
      /* padding-right: 34px; */
      padding-right: 68px;
    }
    .table-header-btn {
      position: absolute;
      right: 0px;
      top: 8px;
      background-color: #f8f8f9;
    }
    th .ivu-table-cell {
      height: 40px;
    }
    /deep/ .ivu-table-footer {
      height: auto !important;
    }
    .top-operation-area {
      display: flex;
      justify-content: space-around;
    }
    .top-btn {
      margin-left: 1px;
      width: 100%;
      display: inline-grid;
      span {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: inline-block;
        width: 100%;
      }
    }
  }

  /deep/ .vertical-center-modal {
    display: flex;
    align-items: center;
    justify-content: center;

    .ivu-modal {
      top: 0px;
      height: 100%;
      .ivu-modal-content {
        height: 100%;
        .ivu-modal-header {
          height: 40px;
        }
        .ivu-modal-body {
          padding: 0px;
          width: 100%;
          position: absolute;
          top: 0px;
          bottom: 0px;
          left: 0px;
        }
        .ivu-modal-footer {
          width: 100%;
          height: 0px;
          padding: 0px;
          position:absolute;
          bottom:0;
        }
      }
    }
  }
</style>
